package com.yh.homestay.service.impl;

import com.yh.homestay.pojo.UserStaff;
import com.yh.homestay.security.SecurityUserStaff;
import com.yh.homestay.service.SysRoleService;
import com.yh.homestay.service.UserStaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserDetailsServiceImpl
 * @Description TODO
 * @Author GCL
 * @Date 2020/1/6 10:16
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserStaffService userStaffService;

    @Autowired
    private SysRoleService sysRoleService;
    
    /**
     * @param staffId 工号
     * @Date: 2020/1/6 12:00
     * @Description: 使用staffId作为用户名，staffName作为密码登录
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String staffId) throws UsernameNotFoundException {
        int staffIdInteger = Integer.parseInt(staffId);
        //从数据库中查询数据
        UserStaff userStaff = userStaffService.selectOneStaff(staffIdInteger);
        if (userStaff == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        List<String> roles = sysRoleService.getRoleName(staffIdInteger);
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (String role:roles) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
            authorities.add(grantedAuthority);
        }
        SecurityUserStaff securityUserStaff = new SecurityUserStaff(userStaff.getStaffId()+"", userStaff.getStaffName(),authorities);
        return securityUserStaff;
    }

}
